<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">




<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
  </script>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />



  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico?v=5.1.4">







  <meta name="keywords" content="iOS," />





  <link rel="alternate" href="/atom.xml" title="Swift社区" type="application/atom+xml" />






<meta name="description" content="前言SwiftUI与苹果之前的UI框架的区别不仅仅在于如何定义视图和其他UI组件，还在于如何在整个使用它的应用程序中管理视图层级的状态。 SwiftUI没有使用委托、数据源或任何其他在UIKit和AppKit等命令式框架中常见的状态管理模式，而是配备了一些属性包装器，使我们能够准确地声明我们的数据如何被我们的视图观察、渲染和改变。 本周，让我们仔细看看这些属性包装器中的每一个，它们之间的关系，以及">
<meta name="keywords" content="iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="SwiftUI 状态管理系统指南">
<meta property="og:url" content="https://fanbaoying.github.io/SwiftUI-状态管理系统指南/index.html">
<meta property="og:site_name" content="Swift社区">
<meta property="og:description" content="前言SwiftUI与苹果之前的UI框架的区别不仅仅在于如何定义视图和其他UI组件，还在于如何在整个使用它的应用程序中管理视图层级的状态。 SwiftUI没有使用委托、数据源或任何其他在UIKit和AppKit等命令式框架中常见的状态管理模式，而是配备了一些属性包装器，使我们能够准确地声明我们的数据如何被我们的视图观察、渲染和改变。 本周，让我们仔细看看这些属性包装器中的每一个，它们之间的关系，以及">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2022-07-06T11:14:54.306Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SwiftUI 状态管理系统指南">
<meta name="twitter:description" content="前言SwiftUI与苹果之前的UI框架的区别不仅仅在于如何定义视图和其他UI组件，还在于如何在整个使用它的应用程序中管理视图层级的状态。 SwiftUI没有使用委托、数据源或任何其他在UIKit和AppKit等命令式框架中常见的状态管理模式，而是配备了一些属性包装器，使我们能够准确地声明我们的数据如何被我们的视图观察、渲染和改变。 本周，让我们仔细看看这些属性包装器中的每一个，它们之间的关系，以及">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://fanbaoying.github.io/SwiftUI-状态管理系统指南/"/>





  <title>SwiftUI 状态管理系统指南 | Swift社区</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    
    <a href="https://github.com/SwiftCommunityRes" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Swift社区</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">做最好的 Swift 社区</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://fanbaoying.github.io/SwiftUI-状态管理系统指南/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Swift社区">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars.githubusercontent.com/u/84354365?v=4">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Swift社区">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">SwiftUI 状态管理系统指南</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-07-06T19:11:56+08:00">
                2022-07-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/SwiftUI/" itemprop="url" rel="index">
                    <span itemprop="name">SwiftUI</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                -->
                <span title="字数统计">
                  数字统计 3,143字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                --> 

                <span title="阅读时长">
                  阅读时长 12分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>SwiftUI与苹果之前的UI框架的区别不仅仅在于如何定义视图和其他UI组件，还在于如何在整个使用它的应用程序中管理视图层级的状态。</p>
<p>SwiftUI没有使用委托、数据源或任何其他在UIKit和AppKit等命令式框架中常见的状态管理模式，而是配备了一些属性包装器，使我们能够准确地声明我们的数据如何被我们的视图观察、渲染和改变。</p>
<p>本周，让我们仔细看看这些属性包装器中的每一个，它们之间的关系，以及它们如何构成SwiftUI整体状态管理系统的不同部分。</p>
<a id="more"></a>
<h2 id="属性状态"><a href="#属性状态" class="headerlink" title="属性状态"></a>属性状态</h2><p>由于SwiftUI主要是一个UI框架（尽管它也开始获得用于定义更高层次结构（如应用程序和场景）的API），其声明式设计不一定需要影响应用程序的整个模型和数据层——而只是直接绑定到我们各种视图的状态。</p>
<p>例如，假设我们正在开发一个<code>SignupView</code>，使用户能够通过输入用户名和电子邮件地址在应用程序中注册一个新账户。我们将使用这两个值形成一个用户模型，并将其传递给一个闭包：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">SignupView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> handler: (<span class="type">User</span>) -&gt; <span class="type">Void</span></span><br><span class="line">    <span class="keyword">var</span> username = <span class="string">""</span></span><br><span class="line">    <span class="keyword">var</span> email = <span class="string">""</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由于这三个属性中只有两个——<code>username</code>和<code>email</code>——实际上会被我们的视图修改，而且这两个状态可以保持私有，我们将使用SwiftUI的<code>State</code>属性包装器来标记它们——像这样：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">SignupView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> handler: (<span class="type">User</span>) -&gt; <span class="type">Void</span></span><br><span class="line">    </span><br><span class="line">    @<span class="type">State</span> <span class="keyword">private</span> <span class="keyword">var</span> username = <span class="string">""</span></span><br><span class="line">    @<span class="type">State</span> <span class="keyword">private</span> <span class="keyword">var</span> email = <span class="string">""</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样做将自动在这两个值和我们的视图本身之间建立一个连接——这意味着我们的视图将在每次改变这两个值的时候被重新渲染。在我们的主体中，我们将把这两个属性分别绑定到一个相应的<code>TextField</code>上，以使它们可以被用户编辑：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">SignupView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> handler: (<span class="type">User</span>) -&gt; <span class="type">Void</span></span><br><span class="line"></span><br><span class="line">    @<span class="type">State</span> <span class="keyword">private</span> <span class="keyword">var</span> username = <span class="string">""</span></span><br><span class="line">    @<span class="type">State</span> <span class="keyword">private</span> <span class="keyword">var</span> email = <span class="string">""</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">VStack</span> &#123;</span><br><span class="line">            <span class="type">TextField</span>(<span class="string">"Username"</span>, text: $username)</span><br><span class="line">            <span class="type">TextField</span>(<span class="string">"Email"</span>, text: $email)</span><br><span class="line">            <span class="type">Button</span>(</span><br><span class="line">                action: &#123;</span><br><span class="line">                    <span class="keyword">self</span>.handler(<span class="type">User</span>(</span><br><span class="line">                        username: <span class="keyword">self</span>.username,</span><br><span class="line">                        email: <span class="keyword">self</span>.email</span><br><span class="line">                    ))</span><br><span class="line">                &#125;,</span><br><span class="line">                label: &#123; <span class="type">Text</span>(<span class="string">"Sign up"</span>) &#125;</span><br><span class="line">            )</span><br><span class="line">        &#125;</span><br><span class="line">        .padding()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因此，<code>State</code>被用来表示SwiftUI视图的内部状态，并在该状态被改变时自动使视图更新。因此，最常见的做法是将<code>State</code>属性包装器保持为私有，这可以确保它们只在该视图的主体内被改变（试图在其他地方改变它们实际上会导致运行时崩溃）。</p>
<h2 id="双向绑定"><a href="#双向绑定" class="headerlink" title="双向绑定"></a>双向绑定</h2><p>看一下上面的代码样本，我们将每个属性传入其<code>TextField</code>的方式是在这些属性名称前加上<code>$</code>。这是因为我们不只是将普通的<code>String</code>值传入这些文本字段，而是与我们的<code>State</code>包装的属性本身绑定。</p>
<p>为了更详细地探讨这意味着什么，让我们现在假设我们想创建一个视图，让我们的用户编辑他们最初在注册时输入的个人资料信息。由于我们现在要修改外部状态值，而不仅仅是私人状态值，所以这次我们将<code>username</code>和<code>email</code>属性标记为<code>Bingding</code>:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ProfileEditingView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">Binding</span> <span class="keyword">var</span> username: <span class="type">String</span></span><br><span class="line">    @<span class="type">Binding</span> <span class="keyword">var</span> email: <span class="type">String</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">VStack</span> &#123;</span><br><span class="line">            <span class="type">TextField</span>(<span class="string">"Username"</span>, text: $username)</span><br><span class="line">            <span class="type">TextField</span>(<span class="string">"Email"</span>, text: $email)</span><br><span class="line">        &#125;</span><br><span class="line">        .padding()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最酷的是，绑定不仅仅局限于单一的内置值，比如字符串或整数，而是可以用来将任何Swift值绑定到我们的一个视图中。例如，我们可以将用户模型本身传递给<code>ProfileEditingView</code>，而不是传递两个单独的<code>username</code>和<code>email</code>:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ProfileEditingView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">Binding</span> <span class="keyword">var</span> user: <span class="type">User</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">VStack</span> &#123;</span><br><span class="line">            <span class="type">TextField</span>(<span class="string">"Username"</span>, text: $user.username)</span><br><span class="line">            <span class="type">TextField</span>(<span class="string">"Email"</span>, text: $user.email)</span><br><span class="line">        &#125;</span><br><span class="line">        .padding()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>就像我们在将<code>State</code>和<code>Binding</code>包装的属性传入各种<code>TextField</code>实例时用<code>$</code>作为前缀一样，我们在将任何<code>State</code>值连接到我们自己定义的<code>Binding</code>属性时也可以做同样的事情。</p>
<p>例如，这里有一个<code>ProfileView</code>的实现，它使用一个<code>Stage</code>包装属性来跟踪一个用户模型，然后在将上述<code>ProfileEditingView</code>的实例作为工作表呈现时，将该模型传递一个绑定——这将自动同步用户对该原始<code>State</code>属性值的任何改变:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ProfileView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">State</span> <span class="keyword">private</span> <span class="keyword">var</span> user = <span class="type">User</span>.load()</span><br><span class="line">    @<span class="type">State</span> <span class="keyword">private</span> <span class="keyword">var</span> isEditingViewShown = <span class="literal">false</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">VStack</span>(alignment: .leading, spacing: <span class="number">10</span>) &#123;</span><br><span class="line">            <span class="type">Text</span>(<span class="string">"Username: "</span>)</span><br><span class="line">                .foregroundColor(.secondary)</span><br><span class="line">                + <span class="type">Text</span>(user.username)</span><br><span class="line">            <span class="type">Text</span>(<span class="string">"Email: "</span>)</span><br><span class="line">                .foregroundColor(.secondary)</span><br><span class="line">                + <span class="type">Text</span>(user.email)</span><br><span class="line">            <span class="type">Button</span>(</span><br><span class="line">                action: &#123; <span class="keyword">self</span>.isEditingViewShown = <span class="literal">true</span> &#125;,</span><br><span class="line">                label: &#123; <span class="type">Text</span>(<span class="string">"Edit"</span>) &#125;</span><br><span class="line">            )</span><br><span class="line">        &#125;</span><br><span class="line">        .padding()</span><br><span class="line">        .sheet(isPresented: $isEditingViewShown) &#123;</span><br><span class="line">            <span class="type">VStack</span> &#123;</span><br><span class="line">                <span class="type">ProfileEditingView</span>(user: <span class="keyword">self</span>.$user)</span><br><span class="line">                <span class="type">Button</span>(</span><br><span class="line">                    action: &#123; <span class="keyword">self</span>.isEditingViewShown = <span class="literal">false</span> &#125;,</span><br><span class="line">                    label: &#123; <span class="type">Text</span>(<span class="string">"Done"</span>) &#125;</span><br><span class="line">                )</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>请注意，我们也可以通过给一个<code>State</code>包装的属性分配一个新的值来改变它——比如我们在 “Done “按钮的动作处理程序中把<code>isEditingViewShown</code>设置为<code>false</code>。</p>
</blockquote>
<p>因此，一个<code>Binding</code>标记的属性在给定的视图和定义在该视图之外的状态属性之间提供了一个双向的连接，而<code>Statr</code>和<code>Binding</code>包装的属性都可以通过在其属性名前加上<code>$</code>来作为绑定物传递。</p>
<h2 id="观察对象"><a href="#观察对象" class="headerlink" title="观察对象"></a>观察对象</h2><p><code>State</code>和<code>Bingding</code>的共同点是，它们处理的是在SwiftUI视图层次结构本身中管理的值。然而，虽然建立一个将所有的状态都保存在其各种视图中的应用程序是肯定可行的，但从架构和关注点分离的角度来看，这通常不是一个好主意，而且很容易导致我们的视图变得相当<a href="https://www.swiftbysundell.com/articles/avoiding-massive-swiftui-views/" target="_blank" rel="noopener">庞大和复杂</a>。</p>
<p>值得庆幸的是，SwiftUI还提供了一些机制，使我们能够将外部模型对象连接到我们的各种视图。其中一个机制是<code>ObservableObject</code>协议，当它与<code>ObservedObject</code>属性包装器结合时，我们可以设置与我们视图层之外管理的引用类型的绑定。</p>
<p>作为一个例子，让我们更新上面定义的<code>ProfileView</code>——通过将管理<code>User</code>模型的责任从视图本身转移到一个新的、专门的对象中。现在，我们可以用许多不同的方式来描述这样一个对象，但由于我们正在寻找创建一个类型来控制我们的一个模型的实例——让我们把它变成一个符合SwiftUI的<code>ObservableObject</code>协议的<a href="https://www.swiftbysundell.com/articles/model-controllers-in-swift/" target="_blank" rel="noopener">模型控制器</a>:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserModelController</span>: <span class="title">ObservableObject</span> </span>&#123;</span><br><span class="line">    @<span class="type">Published</span> <span class="keyword">var</span> user: <span class="type">User</span></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>Published</code>属性包装器用于定义对象的哪些属性在被修改时应让观察通知被触发。</p>
</blockquote>
<p>有了上面的类型，现在让我们回到<code>ProfileView</code>，让它观察新的<code>UserModelController</code>的实例，作为一个<code>ObservedObject</code>，而不是用一个<code>State</code>属性包装器来跟踪我们的用户模型。最重要的是，我们仍然可以很容易地将这个模型绑定到我们的<code>ProfileEditingView</code>上，就像以前一样，因为<code>ObservedObject</code>属性包装器也可以转换为绑定：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ProfileView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">ObservedObject</span> <span class="keyword">var</span> userController: <span class="type">UserModelController</span></span><br><span class="line">    @<span class="type">State</span> <span class="keyword">private</span> <span class="keyword">var</span> isEditingViewShown = <span class="literal">false</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">VStack</span>(alignment: .leading, spacing: <span class="number">10</span>) &#123;</span><br><span class="line">            <span class="type">Text</span>(<span class="string">"Username: "</span>)</span><br><span class="line">                .foregroundColor(.secondary)</span><br><span class="line">                + <span class="type">Text</span>(userController.user.username)</span><br><span class="line">            <span class="type">Text</span>(<span class="string">"Email: "</span>)</span><br><span class="line">                .foregroundColor(.secondary)</span><br><span class="line">                + <span class="type">Text</span>(userController.user.email)</span><br><span class="line">            <span class="type">Button</span>(</span><br><span class="line">                action: &#123; <span class="keyword">self</span>.isEditingViewShown = <span class="literal">true</span> &#125;,</span><br><span class="line">                label: &#123; <span class="type">Text</span>(<span class="string">"Edit"</span>) &#125;</span><br><span class="line">            )</span><br><span class="line">        &#125;</span><br><span class="line">        .padding()</span><br><span class="line">        .sheet(isPresented: $isEditingViewShown) &#123;</span><br><span class="line">            <span class="type">VStack</span> &#123;</span><br><span class="line">                <span class="type">ProfileEditingView</span>(user: <span class="keyword">self</span>.$userController.user)</span><br><span class="line">                <span class="type">Button</span>(</span><br><span class="line">                    action: &#123; <span class="keyword">self</span>.isEditingViewShown = <span class="literal">false</span> &#125;,</span><br><span class="line">                    label: &#123; <span class="type">Text</span>(<span class="string">"Done"</span>) &#125;</span><br><span class="line">                )</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然而，我们的新实现与之前使用的基于状态的实现之间的一个重要区别是，我们的<code>UserModelController</code>现在需要作为初始化器的一部分被<a href="https://www.swiftbysundell.com/articles/different-flavors-of-dependency-injection-in-swift/" target="_blank" rel="noopener">注入</a>到<code>ProfileView</code>中。</p>
<p>除了 “迫使 “我们在代码库中建立一个更明确的依赖关系图之外，原因是一个标有<code>ObservedObject</code>的属性并不意味着对这个属性所指向的对象有任何形式的所有权。</p>
<p>因此，虽然下面的内容在技术上可能会被编译，但最终会导致运行时的问题——因为当我们的视图在更新时被重新创建，<code>UserModelController</code>实例可能会被删除（因为我们的视图现在是它的主要所有者）:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ProfileView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">ObservedObject</span> <span class="keyword">var</span> userController = <span class="type">UserModelController</span>.load()</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>重要的是要记住: SwiftUI视图不是对正在屏幕上渲染的实际UI组件的引用，而是描述我们的UI的轻量级值——因此它们没有像<code>UIView</code>实例那样的生命周期。</p>
</blockquote>
<p>为了解决上述问题，苹果在iOS 14和macOS Big Sur中引入了一个新的属性包装器，名为<code>StateObject</code>。标记为<code>StateObject</code>的属性与<code>ObservedObject</code>的行为完全相同——此外，SwiftUI将确保存储在此类属性中的任何对象不会因为框架在重新渲染视图时重新创建新实例而被意外释放：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ProfileView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">StateObject</span> <span class="keyword">var</span> userController = <span class="type">UserModelController</span>.load()</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>尽管从技术上来说，从现在开始可以只使用<code>StateObject</code>——我仍然建议在观察外部对象时使用<code>ObservedObject</code>，而在处理视图本身拥有的对象时只使用<code>StateObject</code>。把<code>StateObject</code>和<code>ObservedObject</code>看作是<code>State</code>和<code>Binding</code>的参考类型，或者SwiftUI版本的强和弱属性。</p>
<h2 id="观察和修改环境变量"><a href="#观察和修改环境变量" class="headerlink" title="观察和修改环境变量"></a>观察和修改环境变量</h2><p>最后，让我们来看看SwiftUI的环境系统如何被用来在两个互不直接连接的视图之间传递各种状态。尽管在一个父视图和它的一个子视图之间创建绑定通常很容易，但在整个视图层次结构中传递某个对象或值可能相当麻烦——而这正是环境变量旨在解决的问题类型。</p>
<p>有两种主要的方法来使用SwiftUI的环境。一种是首先在想要检索给定对象的视图中定义一个<code>EnvironmentObject</code>包装的属性——例如像这个<code>ArticleView</code>如何检索一个包含颜色信息的<code>Theme</code>对象:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ArticleView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">EnvironmentObject</span> <span class="keyword">var</span> theme: <span class="type">Theme</span></span><br><span class="line">    <span class="keyword">var</span> article: <span class="type">Article</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">VStack</span>(alignment: .leading) &#123;</span><br><span class="line">            <span class="type">Text</span>(article.title)</span><br><span class="line">                .foregroundColor(theme.titleTextColor)</span><br><span class="line">            <span class="type">Text</span>(article.body)</span><br><span class="line">                .foregroundColor(theme.bodyTextColor)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后，我们必须确保在我们的视图的某一个父类中提供我们的环境对象（在这种情况下是一个<code>Theme</code>实例），然后SwiftUI会处理其余的事情。这是通过使用<code>environmentalObject</code>修饰符完成的，例如，像这样：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">RootView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">ObservedObject</span> <span class="keyword">var</span> theme: <span class="type">Theme</span></span><br><span class="line">    @<span class="type">ObservedObject</span> <span class="keyword">var</span> articleLibrary: <span class="type">ArticleLibrary</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">ArticleListView</span>(articles: articleLibrary.articles)</span><br><span class="line">            .environmentObject(theme)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>请注意，我们不需要将上述修改器应用于将使用我们的环境对象的确切视图——我们可以将其应用于我们的层次结构中任何在其之上的视图。</p>
</blockquote>
<p>使用 SwiftUI 环境系统的第二种方式是定义一个自定义的<code>EnvironmentKey</code> ——然后它可以被用来向内置的<code>EnvironmentValues</code> 类型分配和检索值:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ThemeEnvironmentKey</span>: <span class="title">EnvironmentKey</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">var</span> defaultValue = <span class="type">Theme</span>.<span class="keyword">default</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">EnvironmentValues</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> theme: <span class="type">Theme</span> &#123;</span><br><span class="line">        <span class="keyword">get</span> &#123; <span class="keyword">self</span>[<span class="type">ThemeEnvironmentKey</span>.<span class="keyword">self</span>] &#125;</span><br><span class="line">        <span class="keyword">set</span> &#123; <span class="keyword">self</span>[<span class="type">ThemeEnvironmentKey</span>.<span class="keyword">self</span>] = newValue &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>有了上述内容，我们现在可以使用<code>Enviroment</code>属性包装器（而不是<code>EnvironmentObject</code>）来标记我们视图的<code>theme</code>属性，并传入我们希望检索的环境键的<a href="https://www.swiftbysundell.com/articles/the-power-of-key-paths-in-swift" target="_blank" rel="noopener">键值路径</a>:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ArticleView</span>: <span class="title">View</span> </span>&#123;</span><br><span class="line">    @<span class="type">Environment</span>(\.theme) <span class="keyword">var</span> theme: <span class="type">Theme</span></span><br><span class="line">    <span class="keyword">var</span> article: <span class="type">Article</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> body: some <span class="type">View</span> &#123;</span><br><span class="line">        <span class="type">VStack</span>(alignment: .leading) &#123;</span><br><span class="line">            <span class="type">Text</span>(article.title)</span><br><span class="line">                .foregroundColor(theme.titleTextColor)</span><br><span class="line">            <span class="type">Text</span>(article.body)</span><br><span class="line">                .foregroundColor(theme.bodyTextColor)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述两种方法的一个明显区别是，基于键的方法要求我们在编译时定义一个默认值，而基于环境对象<code>EnvironmentObject</code>的方法则假设在运行时提供这样一个值（如果不这样做将导致崩溃）。</p>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>SwiftUI管理状态的方式绝对是该框架最有趣的方面之一，它可能需要我们稍微重新思考数据在应用中的传递方式——至少在涉及到将被我们的UI直接消费和修改的数据时是这样。</p>
<p>我希望这篇指南能成为一个很好的方式来概述SwiftUI的各种状态处理机制，尽管一些更具体的API被遗漏了，这篇文章中强调的概念应该涵盖了所有基于SwiftUI的状态处理的绝大多数用例。</p>
<p>感谢你的阅读! </p>

      
    </div>
    
    
    
    

    
      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    


    
      <div>
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/SwiftUI-状态管理系统指南/">SwiftUI 状态管理系统指南</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Swift社区 的个人博客">Swift社区</a></p>
  <p><span>发布时间:</span>2022年07月06日 - 19:07</p>
  <p><span>最后更新:</span>2022年07月06日 - 19:07</p>
  <p><span>原始链接:</span><a href="/SwiftUI-状态管理系统指南/" title="SwiftUI 状态管理系统指南">https://fanbaoying.github.io/SwiftUI-状态管理系统指南/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://fanbaoying.github.io/SwiftUI-状态管理系统指南/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      </div>
    


    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="Swift社区 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="Swift社区 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"><i class="fa fa-tag"></i> iOS</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/Swift-中的类型占位符/" rel="next" title="Swift 中的类型占位符">
                <i class="fa fa-chevron-left"></i> Swift 中的类型占位符
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/Swift-周报-第十期/" rel="prev" title="Swift 周报 第十期">
                Swift 周报 第十期 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://avatars.githubusercontent.com/u/84354365?v=4"
                alt="Swift社区" />
            
              <p class="site-author-name" itemprop="name">Swift社区</p>
              <p class="site-description motion-element" itemprop="description">我们的使命是做一个最专业最权威的 Swift 中文社区，我们的愿景是希望更多的人学习和使用Swift。我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术干货，不忘初心，牢记使命。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">187</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_36478920" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/5a30d987f265da430d580126" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-spinner"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/fanbaoying" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/swift-community" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/7711465033" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzAxNzgzNTgwMw==&action=getalbum&album_id=2024314764775981057" target="_blank" title="公众号">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftWeekly" title="SwiftWeekly" target="_blank">SwiftWeekly</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/article-ios" title="Article-ios" target="_blank">Article-ios</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftUI-Book" title="SwiftUI-Book" target="_blank">SwiftUI-Book</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#属性状态"><span class="nav-number">2.</span> <span class="nav-text">属性状态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#双向绑定"><span class="nav-number">3.</span> <span class="nav-text">双向绑定</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#观察对象"><span class="nav-number">4.</span> <span class="nav-text">观察对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#观察和修改环境变量"><span class="nav-number">5.</span> <span class="nav-text">观察和修改环境变量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小结"><span class="nav-number">6.</span> <span class="nav-text">小结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Swift社区</span>

  
</div>

<!-- 
<div class="powered-by">
  <i class="fa fa-user-md">
  </i>
  <span id="busuanzi_container_site_uv">
    已有<span id="busuanzi_value_site_uv"></span>人来访
  </span>

</div>


  <span class="post-meta-divider">|</span>


<div class="powered-by">
  <i class="fa fa-eye"></i>
  <span id="busuanzi_container_site_pv">
      访问量<span id="busuanzi_value_site_pv"></span>次
  </span>
</div>



  <span class="post-meta-divider">|</span>


-->

<div class="theme-info">
  <i class="fa fa-pencil"></i>
  <span class="post-count">博客全站共361.6k字</span>
</div>


<!-- 
  <span class="post-meta-divider">|</span>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>



-->

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
